/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Utility.CustomTag;

import Model.ObjectBean.Resource;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.SimpleTagSupport;

/**
 *
 * @author Tran Nguyen Anh Tu
 */
public class ItemListingTag extends SimpleTagSupport {
    //PARAM SETTER
    public void setCol(int col) {
        this.col = col;
    }
    public void setCssID(String cssID) {
        this.cssID = cssID;
    }
    public void setIsmultipage(boolean ismultipage) {
        this.ismultipage = ismultipage;
    }
    public void setItemarray(ArrayList itemarray) {
        this.itemarray = itemarray;
    }
    public void setPagenumber(int pagenumber) {
        if(pagenumber==0)
            this.pagenumber=1;
        else
            this.pagenumber = pagenumber;
    }
    public void setRow(int row) {
        this.row = row;
    }
    public void setContextpath(String contextpath) {
        this.contextpath = contextpath;
    }
    
    //TAG-PARAM
    private int col;
    private int row;
    private String cssID;
    private String contextpath;
   
    private ArrayList itemarray;
    private int pagenumber;     //# of current page
    private boolean ismultipage=false;
    
    //LOCAL ATTRIBUTES
    private int containersize;  //size of container
    private int itempointer;    //pointer for getting an item in array
    private int listsize;       //size of item array
    private int pagecount;      //number of page
    private JspWriter out;
    private String blankimage;
    private String carticon;
  
    ///INITIALIZE LOCAL ATTRIBUTES
    public void initAttributes(){
        out=getJspContext().getOut();
        blankimage="Resources/blank-icon.jpg";
        carticon="Resources/cart-icon.jpg";
        
        containersize=col*row;
        itempointer=containersize*(pagenumber-1);
        listsize=itemarray.size();
        
        //condition: pagecount*containersize >= listsize
        pagecount=itemarray.size()/containersize;
        if(itemarray.size()%containersize!=0) pagecount+=1;
        
    }
    
    ///RENDER AN ITEM LIST WITH GIVEN PARAM
    public void outList() throws JspException, IOException{
        for(int i=0;i<row;i++)
        {
            //Select CSS ID
            out.println("<tr id="+cssID+">");
            for(int j=0;j<col;j++)
            {
                //This condition use for some case that listsize < container-size
                //To prevent NullPointerException from ArrayList
                if(itempointer==listsize) break;
                
                Resource item = (Resource)itemarray.get(itempointer);
                out.println("<td style=\"margin: 10px 10px 10px 10px;padding: 30px 0px 30px 0px;\">");
                //Set a link for img, link destination is ResourceDetailServlet
                out.print("<a href=\"ResourceDetailServlet?resourceID="+item.getRe_id()+"&group="+item.getGroup_id()
                                                +"&category="+item.getCategory_id()+"&publisher="+item.getPublisher_id()+"\">");
                out.println("<img src="+item.getCover_image()+" alt=\"Header image\" width=\"75\" height=\"100\" border=\"0\" /></a>");
                out.println("<br/>");
                //Name, Author, Publish Date and Price ( with cut from discount or not )
                out.println("<div style=\"color:blue\">"+item.getLabel()+"</div>");
                out.println("Tác giả: "+item.getAuthor()+"<br/>");
                out.println("Ngày XB: "+ dateConverter(item.getPublish_date())+"<br/>");
                if(Double.parseDouble(item.getDiscount())==0.0)
                {
                    out.println("Giá: "+ addSpace(item.getPrice())+"<br/>");
                    out.println("</br");
                }
                else 
                {
                    out.println("<div style=\"text-decoration:line-through;\">Giá: "+ addSpace(item.getPrice())+"</div>"); 
                    out.println("<div style=\"color:red;\">KM: "+ addSpace(calculateDiscount(item.getPrice(), item.getDiscount())) +"</div>"); 
                }
                //Check if Item is in stock or not, if not, then cart-icon wont be displayed
                if(Integer.parseInt(item.getSold_number())==0)
                {
                    out.println("<b>Hết hàng</b><br/>");
                    out.println("<img src="+blankimage+" width=\"25\" height=\"25\" border=\"0\" />");
                }
                else
                {
                    out.println("<b>Còn hàng</b><br/>");
                    out.print("<a href=\"CartServlet?resourceID="+item.getRe_id()+"\">");
                    out.println("<img src=\""+carticon+"\" alt=\"Header image\" width=\"25\" height=\"25\" border=\"0\"/>");
                    out.println("</a>");
                }
                //Move pointer to the next item in ArrayList
                itempointer++;
                out.println("</td>");
            }
            //End of row
            out.print("</tr>");
        }
    }
    
    ///CREATE PAGE SELECTOR WITH FORMAT: FIRSTPAGE 1 2 3 4 LAST PAGE
    public void createPageSelector(int pagecount, JspWriter out) throws IOException{
        out.println("<a href=\"SearchServlet?p=1\">"+"Trang đầu  "+"</a>");
        for(int i=1;i<=pagecount;i++){
            out.println("<a href=\"SearchServlet?p="+i+"\">");
            out.println(i+"  ");
            out.println("</a>");
        }
        out.println("<a href=\"SearchServlet?p="+pagecount+"\">"+"Trang cuối"+"</a>");    
    }
    
    //ADD SPACE INTO PRICE (IMPROVE UI)
    //Ex: xxxxxxx -> x xxx xxx
    //Algorithm: 
    //  S1: xxxxxxx
    //  S2: xxxxyyy temp[0]=yyy;
    //  S3: xcccxxx temp[1]=ccc;
    //  S4: zxxxxxx temp[2]=z;
    // result = temp[2]+","+temp[1]+","+temp[0];
    public String addSpace(String price){
        String temp[]=new String[6];
        String result="";
        int i;
        for(i =0;i<price.length()/3;i++)
        {
        temp[i]=price.substring(price.length()-3*(i+1),price.length()-3*i);
        }
        temp[i]=price.substring(0,price.length()-3*i);
        while(i>=0)
        {
            result+=temp[i]+" ";
            i--;
        }
        return result;
    }
    
    //DATE CONVERTER (IMPROVE UI)
    //Convert from yyyy/mm/dd to dd/mm/yyyy
    public String dateConverter(String date){
        String[] temp=date.split("-",3);
        return temp[2]+"/"+temp[1]+"/"+temp[0];
    }
    
    //CALCULATE DISCOUNTED PRICE
    public String calculateDiscount(String price, String discount){
        int Price = Integer.parseInt(price);
        DecimalFormat df = new DecimalFormat("#"); 
        double Discount=Double.parseDouble(discount);
        return df.format(Price*(1-Discount));
    }
    //FUNCTION
    public void doTag() throws JspException, IOException{       
        initAttributes();
        outList();
        //If caller page allows multi-page, following codes will create a multi-page selector
        //If array size is 0, page selector wont be created
        if(!itemarray.isEmpty()){
            if(ismultipage)
            {
                out.print("<tr>");
                out.print("<td colspan=\""+col+"\" style=\"text-align:right;text-decoration:none;\">");
                    createPageSelector(pagecount,out);
                out.print("</td>");
            }
        }
    }   
}
